package com.cssnj.portal.service.common;

import com.cssnj.portal.domain.common.GeneralConstants;
import com.cssnj.portal.domain.common.UserInfo;
import com.cssnj.portal.domain.func.GlGnEntity;
import com.cssnj.portal.domain.func.GlGnRepository;
import com.cssnj.portal.utils.RedisUtil;
import com.cssnj.portal.utils.TreeUtil;
import io.predictech.framework.domain.common.JsonRequest;
import io.predictech.framework.domain.common.JsonResponse;
import io.predictech.framework.domain.common.TreeNode;
import io.predictech.framework.domain.constants.SysConstants;
import io.predictech.framework.domain.exception.BaseException;
import io.predictech.framework.service.base.BaseService;
import io.predictech.framework.utility.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

@Service("treeService")
public class TreeService extends BaseService {

    @Autowired
    private GlGnRepository glGnRepository;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    protected JsonResponse invokingService(JsonRequest jsonRequest) throws SQLException, BaseException {
        switch (jsonRequest.getHandleCode()) {
            case "gnJsTree":
                return gnJsTree(jsonRequest);
            case "allTree":
                return allTree(jsonRequest);
            case "searchGnByMc":
                return searchGnByMc(jsonRequest);
            case "getFunc":
                return getFunc(jsonRequest);
            case "jiaoHuan":
                return jiaoHuan(jsonRequest);
            case "getGnChildPx":
                return getGnChildPx(jsonRequest);
        }
        return null;
    }


    /**
     * @description 获取所有菜单(异步加载下级菜单 调用初始菜单参数应为 0)
     * 1 == needLeaf 获取叶子节点 else 只获取文件夹
     * @author Arthur
     * @since 2018/9/11 22:13
     **/
    public JsonResponse getFunc(JsonRequest jsonRequest) {
        JsonResponse jsonResponse = new JsonResponse();

        String funcId = jsonRequest.getReqData().get("funcId").toString().toLowerCase();
        String needLeaf = StringUtil.empty(jsonRequest.getReqData().get("needLeaf"));

        // 聚合所有菜单
        List<GlGnEntity> menuList = glGnRepository.findAll()
                .parallelStream()
                // 上级功能ID
                .filter(gnEntity -> funcId.equals(gnEntity.getSjgnId()))
                // 是否需要叶子节点 | 打开方式
                .filter(gnEntity -> "1".equals(needLeaf) || "0".equals(gnEntity.getOpenType()))
                // 显示功能
                .filter(gnEntity -> "1".equals(gnEntity.getXsBj()))
                // 选用功能
                .filter(gnEntity -> "1".equals(gnEntity.getXyBj()))
                // 非本系统功能
                .filter(gnEntity -> !GeneralConstants.XT_DM.equals(gnEntity.getXtDm()))
                .collect(Collectors.toList());

        jsonResponse.getRepData().put("funcList", menuList);

        return jsonResponse;
    }

    protected JsonResponse gnJsTree(JsonRequest jsonRequest) throws SQLException, BaseException {
        JsonResponse jsonResponse = new JsonResponse();
        String role = (String) jsonRequest.getReqData().get("role");
        List<Map<String, Object>> gnlist;
        List<Object> params = new ArrayList<Object>();

        if (role.equals(SysConstants.SYS_USER_ADMIN)) {//管理员查询全部可以菜单
            gnlist = queryDao.queryForList(
                    " SELECT 'TRUE' CHECKED , GN_ID, GN_MC, SJGN_ID,  HREF, OPEN_TYPE,PX " +
                            "  FROM GL_GN   " +
                            " WHERE XY_BJ = '1' AND XS_BJ='1'  ORDER BY DECODE(OPEN_TYPE,'0',0,1), PX ", params);
        } else {
            params.add(role);
            gnlist = queryDao.queryForList(
                    "SELECT DECODE(B.GN_ID, NULL, 'FALSE', 'TRUE') CHECKED,\n" +
                            "       A.GN_ID,\n" +
                            "       A.GN_MC,\n" +
                            "       A.SJGN_ID,\n" +
                            "       A.HREF,\n" +
                            "       A.OPEN_TYPE,PX\n" +
                            "  FROM GL_GN A, (SELECT GN_ID FROM GL_JS_GN WHERE JS_ID = ?) B\n" +
                            " WHERE A.GN_ID = B.GN_ID(+)\n" +
                            "   AND A.XY_BJ = '1'\n" +
                            "   AND A.XS_BJ = '1'  ORDER BY DECODE(OPEN_TYPE,'0',0,1), PX ", params);
        }

        List<Map<String, Object>> treelist = new ArrayList<Map<String, Object>>();
        Map<String, Object> map;
        for (Map<String, Object> data : gnlist) {
            map = new HashMap();
            map.put(TreeNode.ID.getKey(), data.get("GN_ID"));
            map.put(TreeNode.TEXT.getKey(), data.get("GN_MC"));
            map.put(TreeNode.PID.getKey(), data.get("SJGN_ID"));
            map.put(TreeNode.MODE.getKey(), data.get("OPEN_TYPE"));
            map.put(TreeNode.HREF.getKey(), data.get("HREF"));
            String checked = (String) data.get("CHECKED");
            if ("TRUE".equals(checked)) {
                map.put(TreeNode.CHECKED.getKey(), true);
            } else {
                map.put(TreeNode.CHECKED.getKey(), false);
            }
            map.put(TreeNode.SORT.getKey(), data.get("PX"));
            treelist.add(map);
        }
        jsonResponse.getRepData().put("treelist", TreeUtil.toChlidrenListTree(treelist, "open"));

        return jsonResponse;
    }

    protected JsonResponse allTree(JsonRequest jsonRequest) {
        JsonResponse jsonResponse = new JsonResponse();
        List<String> params = new ArrayList<String>();
        Map<String, Object> map;
        List<Map<String, Object>> treeList = new ArrayList<Map<String, Object>>();
        String sql = "SELECT GN_ID, GN_MC, GN_MC ||'（'|| DECODE(XY_BJ, '1', '启用', '停用') || '）' XS_MC, XY_BJ, SJGN_ID,  OPEN_TYPE,(CASE WHEN JDYS IS NOT NULL THEN 'noBack ' END)||DECODE(SJGN_ID,'0','ml ','')||JDYS ICONCLS,PX FROM GL_GN WHERE XS_BJ = '1' ORDER BY DECODE(OPEN_TYPE,'0',0,1), PX";
        SqlRowSet rs = this.queryDao.queryForRowSet(sql, params);
        while (rs.next()) {
            map = new HashMap<String, Object>();
            map.put(TreeNode.ID.getKey(), rs.getString("GN_ID"));
            map.put(TreeNode.TEXT.getKey(), rs.getString("XS_MC"));
            map.put(TreeNode.TEXT_REAL.getKey(), rs.getString("GN_MC"));
            map.put(TreeNode.PID.getKey(), rs.getString("SJGN_ID"));
            map.put(TreeNode.MODE.getKey(), rs.getString("OPEN_TYPE"));
            map.put(TreeNode.ENABLE.getKey(), rs.getString("XY_BJ"));
            map.put(TreeNode.SORT.getKey(), rs.getString("PX"));
            map.put(TreeNode.ICONCLS.getKey(), rs.getString("ICONCLS"));
            if ("0".equals(map.get(TreeNode.MODE.getKey()))) {
                map.put(TreeNode.STATE.getKey(), "closed");
            }
            treeList.add(map);
        }
        jsonResponse.getRepData().put("treeList", treeList);
        return jsonResponse;
    }

    //根据名称检索菜单
    protected JsonResponse searchGnByMc(JsonRequest jsonRequest) throws SQLException {
        JsonResponse jsonResponse = new JsonResponse();
        UserInfo userInfo = (UserInfo) jsonRequest.getReqData().get("userInfo");
        String searchText = (String) jsonRequest.getReqData().get("searchText");
        // 聚合所有菜单
        List<Map<String, Object>> menuList = RedisUtil.getUserTreelist(redisTemplate, userInfo.getSwrySfDm())
                .parallelStream()
                // 上级功能ID
                .filter(map -> map.get(TreeNode.TEXT.getKey()).toString().indexOf(searchText) > -1)
                // 打开方式非文件夹
                .filter(map -> !"0".equals(TreeNode.MODE.getKey())).collect(Collectors.toList());
        //查询服务厂商
        for (Map<String, Object> map : menuList) {
            String fwcsId = this.getValueByDmCode("FWCS_ID", "YY_ID", (String) map.get("XTDM"), "YY_JCXX");
            map.put("FWCS", this.getValueByDmCode("FWCS_MC", "FWCS_ID", fwcsId, "GL_FWCS"));
        }
        jsonResponse.getRepData().put("list", menuList);
        return jsonResponse;
    }

    /**
     * 功能排序交换
     *
     * @return
     */
    @Transactional
    protected JsonResponse jiaoHuan(JsonRequest jsonRequest) throws SQLException {

        JsonResponse jsonResponse = new JsonResponse();
        String gn_id_1 = (String) jsonRequest.getReqData().get("gn_id_1");
        String gn_id_2 = (String) jsonRequest.getReqData().get("gn_id_2");

        List<Object> params = new ArrayList<Object>();
        params.add(gn_id_1);
        Map map = queryDao.queryForMap("SELECT PX FROM GL_GN WHERE GN_ID = ? \n ", params);
        String px1 = map.get("PX").toString();

        params.clear();
        params.add(gn_id_2);
        map = queryDao.queryForMap("SELECT PX FROM GL_GN WHERE GN_ID = ? \n ", params);
        String px2 = map.get("PX").toString();

        params.clear();
        params.add(px2);
        params.add(gn_id_1);
        baseDao.getJdbcTemplate().update("UPDATE GL_GN SET PX=? WHERE GN_ID=?", params.toArray());

        params.clear();
        params.add(px1);
        params.add(gn_id_2);
        baseDao.getJdbcTemplate().update("UPDATE GL_GN SET PX=? WHERE GN_ID=?", params.toArray());

        return jsonResponse;
    }

    /**
     * @param jsonRequest
     * @return
     * @throws SQLException
     */
    protected JsonResponse getGnChildPx(JsonRequest jsonRequest) throws SQLException {
        JsonResponse jsonResponse = new JsonResponse();
        String sjgn_id = (String) jsonRequest.getReqData().get("sjgn_id");
        List<Object> params = new ArrayList<Object>();
        params.add(sjgn_id);
        Map map = queryDao.queryForMap("SELECT NVL(MAX(PX), 0) + 1 NEXTPX FROM GL_GN WHERE SJGN_ID = ? \n ", params);
        String nextpx = String.valueOf(map.get("NEXTPX"));
        jsonResponse.getRepData().put("nextpx", nextpx);
        return jsonResponse;
    }


}
